import pygame
import random

# 初始化 Pygame
pygame.init()

# 设置屏幕尺寸
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))

# 设置游戏标题
pygame.display.set_caption("Dodge the Meteors")

# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)

# 设置飞船尺寸
player_width = 50
player_height = 60

# 定义玩家类
class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface([player_width, player_height])
        self.image.fill(BLUE)
        self.rect = self.image.get_rect()
        self.rect.x = screen_width // 2 - player_width // 2
        self.rect.y = screen_height - player_height - 10
        self.speed_x = 0

    def update(self):
        self.rect.x += self.speed_x
        # 边界检测
        if self.rect.x < 0:
            self.rect.x = 0
        elif self.rect.x > screen_width - player_width:
            self.rect.x = screen_width - player_width

# 定义陨石类
class Meteor(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface([20, 20])
        self.image.fill(RED)
        self.rect = self.image.get_rect()
        self.rect.x = random.randint(0, screen_width - 20)
        self.rect.y = random.randint(-100, -20)
        self.speed_y = random.randint(5, 15)

    def update(self):
        self.rect.y += self.speed_y
        # 如果陨石超出屏幕，则重置位置
        if self.rect.y > screen_height:
            self.rect.y = random.randint(-100, -20)
            self.rect.x = random.randint(0, screen_width - 20)
            self.speed_y = random.randint(5, 15)

# 创建精灵组
all_sprites = pygame.sprite.Group()
meteors = pygame.sprite.Group()

# 创建玩家实例
player = Player()
all_sprites.add(player)

# 创建陨石实例
for i in range(10):
    meteor = Meteor()
    all_sprites.add(meteor)
    meteors.add(meteor)

# 设置时钟
clock = pygame.time.Clock()

# 游戏主循环
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                player.speed_x = -5
            elif event.key == pygame.K_RIGHT:
                player.speed_x = 5
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                player.speed_x = 0

    # 更新所有精灵
    all_sprites.update()

    # 检测碰撞
    if pygame.sprite.spritecollideany(player, meteors):
        running = False

    # 绘制
    screen.fill(BLACK)
    all_sprites.draw(screen)

    # 刷新屏幕
    pygame.display.flip()

    # 设置帧率
    clock.tick(30)

# 退出 Pygame
pygame.quit()